package day09demo2;

public class StudentTest1 {
    public static void main(String[] args) {
        Student[] arr = new Student[3];
        Student s1 = new Student(1, "日富美", 18);
        Student s2 = new Student(2, "花子", 19);
        Student s3 = new Student(3, "小春", 16);
        arr[0] = s1;
        arr[1] = s2;
        arr[2] = s3;
        Student s4 = new Student(4, "梓", 17);
        boolean flag = flag(arr, s4.getId());
        if (!flag) {
            //原数组中是否存在空位，存在 不考虑情况直接存，不然创建新数组
            int count = getCount(arr);
            if (count != arr.length) {
                arr[count] = s4;
                print(arr);
            } else {
                Student[] newArr = creatNewArr(arr);
                newArr[count] = s4;
                print(newArr);
            }

        } else {
            System.out.println("当前输入学生已经存在");
        }
    }

    //遍历数组 打印
    public static void print(Student[] arr) {
        for (int i = 0; i < arr.length; i++) {
            Student s = arr[i];
            System.out.println(s.getId() + "," + s.getName() + "," + s.getAge());
        }
    }

    //创建+1null的新数组 接收新对象
    public static Student[] creatNewArr(Student[] arr) {
        Student[] newArr = new Student[arr.length + 1];
        for (int i = 0; i < arr.length; i++) {
            Student s = arr[i];
            newArr[i] = s;
        }
        return newArr;
    }

    //遍历数组 找到不为null的个数
    public static int getCount(Student[] arr) {
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            Student s = arr[i];
            if (s != null) {
                count++;
            }
        }
        return count;
    }

    //数组中是否存在 一样的数值
    public static boolean flag(Student[] arr, int id) {
        for (int i = 0; i < arr.length; i++) {
            Student s = arr[i];
            if (s != null) {
                int number = s.getId();
                if (number != id) {
                    return true;
                }
            }
        }
        return false;
    }
}
